<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.product_name" placeholder="请输入 名称 | 规格" clearable style="width: 200px;" class="filter-item" @input="handleSearch" />
      <el-select v-model="listQuery.category" placeholder="一级分类" class="filter-item" style="width: 130px" @change="handleSelectChange">
        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.sub_category" placeholder="二级分类" class="filter-item" style="width: 130px" @change="handleSearch">
        <el-option v-for="item in subCategoryOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="100px">
        <template slot-scope="{row}">
          <div><el-link type="primary">{{ row.category.parent.name }}></el-link></div>
          <div><el-link type="danger">{{ row.category.name }}</el-link></div>
        </template>
      </el-table-column>
      <el-table-column label="主图" width="100px">
        <template slot-scope="{row}">
          <el-image
            style="width: 80px; height: 80px;"
            :src="row.cover.url"
          />
        </template>
      </el-table-column>
      <el-table-column label="名称" width="170px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
          <el-tag type="danger" size="mini" effect="dark" v-if="row.discount && row.discount < 100">{{ row.discount }}%</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="规格">
        <template slot-scope="{row}">
          <div
            v-for="item in row.items"
            :key="item.index"
            style="margin-bottom: 10px"
          >
            <el-tag
              type="success"
            >
              规格名称：{{ item.name }}
            </el-tag>
            <el-tag
              type="info"
            >
              货号：{{ item.sku_no }}
            </el-tag>
            <el-tag
              type="danger"
            >
              单价：{{ item.price }}
            </el-tag>
            <el-tag
              type="danger"
            >
              会员价：{{ item.member_price }}
            </el-tag>
            <el-tag>
              库存：{{ item.stock }}
            </el-tag>
            <el-tag>
              最低库存：{{ item.min_stock }}
            </el-tag>
            <el-tag type="warming">
              最高库存：{{ item.max_stock }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="135px" align="center">
        <template slot-scope="{row}">
          <div>
            上架：
            <el-switch
              v-model="row.sell"
              active-color="#13CE66"
              @change="handleParamChange($event,row,'sell')"
            >
            </el-switch>
          </div>
          <div>
            热门：
            <el-switch
              v-model="row.hot"
              active-color="#13CE66"
              @change="handleParamChange($event,row,'hot')"
            >
            </el-switch>
          </div>

          <div>
            新品专区：
            <el-switch
              v-model="row.new_flag"
              active-color="#13CE66"
              @change="handleParamChange($event,row,'new_flag')"
            >
            </el-switch>
          </div>

          <div>
            每日特价：
            <el-switch
              v-model="row.special_flag"
              active-color="#13CE66"
              @change="handleParamChange($event,row,'special_flag')"
            >
            </el-switch>
          </div>

          <div>
            量大优惠：
            <el-switch
              v-model="row.lot_flag"
              active-color="#13CE66"
              @change="handleParamChange($event,row,'lot_flag')"
            >
            </el-switch>
          </div>

        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230">
        <template slot-scope="{row,$index}">
          <el-button type="warning" size="mini" @click="handleCreateCopy(row)">复制</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger"  size="mini" @click="handleDelete(row, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-drawer
      direction="ltr"
      size="80%"
      :visible.sync="dialogFormVisible"
    >
      <div style="width:80%;margin:0 auto;">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="top" label-width="120px" style="width:100%; margin-left:50px;height:800px;overflow-y: scroll">
          <el-form-item label="分类" prop="category_id">
            <el-cascader
              v-model="temp.category_id"
              :options="cateList"
              :props="{ expandTrigger: 'hover' }"
            />
          </el-form-item>
          <el-form-item label="主图(最多5张)">
            <el-upload
              action="xxx"
              :multiple="true"
              :file-list="fileList"
              list-type="picture-card"
              :on-remove="onRemovePic"
              :on-preview="onPreview"
              :http-request="handleUploadPic"
              :auto-upload="true"
              :limit="5"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="temp.name" />
          </el-form-item>
          <el-form-item label="包装信息" prop="package">
            <el-input v-model="temp.package" placeholder="比如 20个/箱" />
          </el-form-item>
          <el-form-item label="折扣标识" prop="discount">
            <el-input v-model="temp.discount" placeholder="请输入小于10整数，比如8，则显示8折" />
          </el-form-item>
          <el-form-item label="规格信息">
            <el-link type="primary" @click="handleAddItem">新增规格</el-link>
            <el-link type="primary" style="margin-left:20px" @click="handleAddItemCopy">复制新增规格</el-link>
            <el-table
              :data="temp.items"
              border
              style="margin-top: 10px; margin-bottom: 20px"
            >
              <el-table-column label="规格名称" size="mini" prop="name" align="left" width="280">
                <template slot-scope="{row}">
                  <el-input v-model="row.name" />
                </template>
              </el-table-column>
              <el-table-column label="价格" prop="price" align="left" width="100">
                <template slot-scope="{row}">
                  <el-input
                    v-model="row.price"
                    oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                  />
                </template>
              </el-table-column>
              <el-table-column label="会员价" prop="member_price" align="left" width="100">
                <template slot-scope="{row}">
                  <el-input
                    v-model="row.member_price"
                    oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                  />
                </template>
              </el-table-column>
              <el-table-column label="采购价" prop="purchase_price" align="left" width="100">
                <template slot-scope="{row}">
                  <el-input
                    v-model="row.purchase_price"
                    oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                  />
                </template>
              </el-table-column>
              <el-table-column label="库存" prop="stock" align="left" width="100">
                <template slot-scope="{row}">
                  <el-input
                    v-model="row.stock"
                    :disabled="row.id != null"
                    oninput="value=value.replace(/[^\d]/g,'')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="最低库存" prop="min_stock" align="left" width="100">
                <template slot-scope="{row}">
                  <el-input
                    v-model="row.min_stock"
                    oninput="value=value.replace(/[^\d]/g,'')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="最高库存" prop="max_stock" align="left" width="100">
                <template slot-scope="{row}">
                  <el-input
                    v-model="row.max_stock"
                    oninput="value=value.replace(/[^\d]/g,'')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="left" width="100">
                <template slot-scope="{row,$index}">
                  <el-link type="danger" @click="handleDeleteItem(row,$index)">删除规格</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="temp.detail" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入商品描述" />
          </el-form-item>
          <el-form-item>
            <el-button @click="dialogFormVisible = false">
              {{ $t('table.cancel') }}
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              {{ $t('table.confirm') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import { fetchList, uploadFile, addProduct, deleteProduct, updateProduct, updateProductItem, addProductItem, deleteProductItem, updateProductParam } from '@/api/product'
import Pagination from '@/components/Pagination'
import { process } from '@/api/order' // secondary package based on el-pagination

export default {
  name: 'Product',
  components: { Pagination },
  data() {
    return {
      categoryOptions: [{
        value: 0,
        label: '全部'
      }],
      subCategoryOptions: [{
        value: 0,
        label: '全部'
      }],
      image_file_ids: [],
      cateList: [],
      fileList: [],
      deleteItemList: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        category: 0,
        sub_category: 0,
        category_id: '',
        product_name: ''
      },
      temp: {
        category_id: '',
        name: '',
        hot: 1,
        sell: 0,
        description: '暂无描述',
        detail: '暂无描述',
        warehouse_id: '1',
        image_file_id: [],
        cover_file_id: null,
        package: '',
        discount: null,
        items: [{
          name: '',
          price: '',
          stock: '',
          min_stock: '',
          max_stock: '',
          member_price: '',
          purchase_price: ''
        }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        category_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  async created() {
    this.getList()
    const cateList = await this.$store.dispatch('product/getCateList')
    this.cateList = cateList
    this.categoryOptions = this.categoryOptions.concat(cateList)
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.products
        this.total = response.total
        this.listLoading = false
      }).catch(error => {
        this.list = []
        this.total = 0
        this.listLoading = false
        Promise.reject(error)
      })
    },
    handleAddItem() {
      this.temp.items.push({
        name: '',
        stock: '',
        min_stock: '',
        price: '',
        member_price: '',
        purchase_price: ''
      })
    },
    handleAddItemCopy() {
      const item = this.temp.items[0]
      this.temp.items.push({
        name: item.name,
        price: item.price,
        member_price: item.member_price,
        purchase_price: item.purchase_price,
        stock: item.stock,
        min_stock: item.min_stock,
        max_stock: item.max_stock
      })
    },
    handleDeleteItem(row, index) {
      if (this.temp.items.length === 1) {
        this.$notify.error({
          title: '失败',
          message: '至少保留一个规格',
          duration: 2000
        })
        return
      }
      if (row.id) {
        this.deleteItemList.push(row.id)
      }
      this.temp.items.splice(index, 1)
    },
    onRemovePic(file, fileList) {
      const list = this.image_file_ids
      for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].uid === file.uid) {
          this.image_file_ids.splice(i, 1)
          break
        }
      }
    },
    async handleUploadPic(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      const list = this.image_file_ids
      list.push({
        uid: data.file.uid,
        fid: res.file.id
      })
      this.image_file_ids = list
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        category_id: '',
        name: '',
        hot: 1,
        sell: 1,
        description: '暂无描述',
        detail: '暂无描述',
        warehouse_id: '1',
        image_file_id: [],
        cover_file_id: null,
        package: '',
        discount: null,
        items: [{
          name: '',
          price: '',
          member_price: '',
          purchase_price: '',
          stock: '',
          min_stock: '',
          max_stock: ''
        }]
      }
      this.fileList = []
    },
    handleCreate() {
      this.resetTemp()
      this.image_file_ids = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.image_file_ids.length === 0) {
            this.$message({
              message: '请至少上传一张主图',
              type: 'error'
            })
            return
          }
          const data = this.temp
          let nullFlag = false
          data.items.forEach(item => {
            item.cover_file_id = this.image_file_ids[0].fid
            if (item.name === '' || item.price === '' || item.stock === '' || item.member_price === '' || item.purchase_price === '' || item.min_stock === '' || item.max_stock === '') {
              this.$message({
                message: '规格信息不能为空',
                type: 'error'
              })
              nullFlag = true
            }
          })
          if (nullFlag) {
            return
          }
          const imageList = []
          let flag = false
          data.category_id = data.category_id[1]
          this.image_file_ids.forEach(item => {
            imageList.push(item.fid)
            if (data.cover_file_id === item.fid) {
              // eslint-disable-next-line no-const-assign
              flag = true
            }
          })
          if (!flag) {
            data.cover_file_id = imageList[0]
          }
          data.image_file_id = imageList
          if (!data.cover_file_id) {
            data.cover_file_id = data.image_file_id[0]
          }
          addProduct(data).then(res => {
            this.list.unshift(res.product)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.deleteItemList = []
      this.temp = Object.assign({}, row) // copy obj
      this.temp.category_id = []
      this.temp.category_id.push(row.category.parent.id)
      this.temp.category_id.push(row.category.id)
      this.temp.cover_file_id = row.cover.id
      this.fileList = row.images
      this.fileList.forEach(item => {
        item.uid = item.id
      })
      const list = []
      row.images.forEach(item => {
        list.push({
          uid: item.id,
          fid: item.id
        })
      })
      this.image_file_ids = list
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    handleParamChange: async function(val,row,param){
      let data = {}
      data[param] = val
      row[param] = val
      let res = await updateProductParam(row.id,data)
      if(res){
        let index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1, row)
      }
    },

    handleCreateCopy(row) {
      this.resetTemp()
      this.deleteItemList = []
      this.image_file_ids = []
      this.temp = Object.assign({}, row) // copy obj
      this.temp.category_id = []
      this.temp.category_id.push(row.category.parent.id)
      this.temp.category_id.push(row.category.id)
      this.temp.warehouse_id = row.warehouse.id
      this.temp.package = row.package
      this.temp.discount = row.discount
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.temp.items.forEach(item =>{
        item.id = null
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.image_file_ids.length === 0) {
            this.$message({
              message: '请至少上传一张主图',
              type: 'error'
            })
            return
          }
          const tempData = Object.assign({}, this.temp)
          tempData.warehouse_id = '1'
          let nullFlag = false
          tempData.items.forEach(item => {
            item.cover_file_id = this.image_file_ids[0].fid
            if (item.name === '' || item.price === '' || item.stock === '' || item.member_price === '' || item.purchase_price === '' || item.min_stock === '') {
              this.$message({
                message: '规格信息不能为空',
                type: 'error'
              })
              nullFlag = true
            }
          })
          if (nullFlag) {
            return
          }
          tempData.category_id = tempData.category_id[1]
          const imageList = []
          let flag = false
          this.image_file_ids.forEach(item => {
            imageList.push(item.fid)
            if (tempData.cover_file_id === item.fid) {
              flag = true
            }
          })
          if (!flag) {
            tempData.cover_file_id = imageList[0]
          }
          tempData.image_file_id = imageList
          tempData.items.forEach(async function(item) {
            if (item.id) {
              await updateProductItem(tempData.id, item.id, item)
            } else {
              await addProductItem(tempData.id, item)
            }
          })
          this.deleteItemList.forEach(async function(item) {
            await deleteProductItem(tempData.id, item)
          })
          updateProduct(tempData.id, tempData).then(res => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, res.product)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('是否确定删除商品？删除后无法找回', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProduct(row.id).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        }).catch(error => {
          Promise.reject(error)
        })
      })

    },
    handleSelectChange() {
      const id = this.listQuery.category
      const list = [{
        value: 0,
        label: '全部'
      }]
      if (id === 0) {
        this.subCategoryOptions = list
      } else {
        const index = this.categoryOptions.findIndex(v => v.value === id)
        const item = this.categoryOptions[index]
        this.subCategoryOptions = list.concat(item.children)
      }
      this.listQuery.sub_category = 0
      this.handleSearch()
    },
    handleSearch() {
      this.list = []
      this.listQuery.page = 1
      this.getList()
    },
    onPreview(e) {
      this.image_file_ids.forEach(item => {
        if (e.uid === item.uid) {
          this.temp.cover_file_id = item.fid
          this.$notify({
            title: '成功设置主图',
            type: 'success',
            duration: 1000
          })
        }
      })
    }
  }
}
</script>
